package com.hepinghospital.user.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.gyf.immersionbar.ImmersionBar;
import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.eventbus.Logout;
import com.hepinghospital.user.ui.MainActivity;
import com.hepinghospital.user.ui.activity.nursing.MyNursingOrderActivity;
import com.hepinghospital.user.ui.activity.nursing.NursingOrderDetailActivity;
import com.hepinghospital.user.ui.activity.userinfo.SettingActivity;
import com.hepinghospital.user.ui.widget.YPayLoadingView;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    @BindView(R.id.tv_result)
    TextView tv_result;
    @BindView(R.id.tv_info)
    TextView tv_info;
    @BindView(R.id.tv_info2)
    TextView tv_info2;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.iv_pay_result)
    ImageView ivPayResult;
    @BindView(R.id.payLoadingView)
    YPayLoadingView mPayLoadingView;

    private IWXAPI api;
    int errorCode, type;
    private boolean isFail = false;
    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_payresult );
        ButterKnife.bind( this );
        ImmersionBar.with( this ).keyboardEnable( true ).fitsSystemWindows( true ).statusBarColor( R.color.white ).navigationBarColor( R.color.black ).autoDarkModeEnable( true ).init();

        api = WXAPIFactory.createWXAPI( this, BaseApplication.currentWXId );
        api.handleIntent( getIntent(), this );
        type = getIntent().getIntExtra( "type", 0 );
        if (type == 1) {
            queryPrepaidOrder();
            queryOrderStatus();
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent( intent );
        setIntent( intent );
        api.handleIntent( intent, this );
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        mPayLoadingView.startLoading();
        Log.e( "----->errCode------ ", resp.errCode + "--" + resp.errStr );
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            errorCode = resp.errCode;
            if (BaseResp.ErrCode.ERR_OK == errorCode) {
                ivPayResult.setVisibility( View.GONE );
                mPayLoadingView.setVisibility( View.VISIBLE );
                ivPayResult.setImageDrawable( ContextCompat.getDrawable( this, R.mipmap.icon_pay_success ) );
                queryPrepaidOrder();
                mTimeCounterRunnable.run();
            } else if (BaseResp.ErrCode.ERR_USER_CANCEL == errorCode) {
                mPayLoadingView.showResult( false );
                ivPayResult.setVisibility( View.VISIBLE );
                mPayLoadingView.setVisibility( View.GONE );
                ivPayResult.setImageDrawable( ContextCompat.getDrawable( this, R.mipmap.quxiao ) );
                tv_result.setText( "支付取消" );
            } else {
                mPayLoadingView.showResult( false );
                isFail = true;
                ivPayResult.setVisibility( View.VISIBLE );
                mPayLoadingView.setVisibility( View.GONE );
                ivPayResult.setImageDrawable( ContextCompat.getDrawable( this, R.mipmap.quxiao ) );
                btnConfirm.setText( "帮助中心" );
                tv_result.setText( "支付失败" );
            }
        }
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        if (BaseApplication.isNursingPay) {
            BaseApplication.isNursingPay = false;
            if (BaseApplication.isNursiningList) {
                finish();
                BaseApplication.isNursiningList = false;
            } else {
                NursingOrderDetailActivity.clsoeSelf();
                startActivity( new Intent( this, MyNursingOrderActivity.class ) );
                finish();
            }
            return;
        }
        if (errorCode == 0) {
            startActivity( new Intent( this, MainActivity.class ) );
            EventBus.getDefault().postSticky( new Logout( 2 ) );
        } else if (isFail) {
            //帮助中心
            startActivity( new Intent( this, SettingActivity.class ) );
        }
        finish();
    }

    private void queryOrderStatus() {
        RestProxy.getInstance().queryOrderStatus( BaseApplication.currentOrderId, new BaseObserver<String>() {
            @Override
            public void onSuccess(String s) {
                //关闭定时任务
                if (mTimeCounterRunnable != null) {
                    mHandler.removeCallbacks( mTimeCounterRunnable );
                }
                mPayLoadingView.showResult( true );
                if (BaseApplication.diagnoseType == 1) {
                    tv_info.setText( BaseApplication.bookInfo );
                    tv_info2.setVisibility( View.VISIBLE );
                } else if (BaseApplication.diagnoseType == 0) {
                    tv_info.setText( BaseApplication.bookInfo );
                } else {
                    tv_info.setVisibility( View.GONE );
                    tv_info2.setVisibility( View.GONE );
                }
                tv_result.setText( "支付成功" );
            }

            @Override
            public void onError(@NotNull Throwable e) {
                mPayLoadingView.showResult( false );
                tv_result.setText( "支付失败" );
            }
        } );
    }

    @Deprecated
    private void queryAppointmentOrderStatus() {
        RestProxy.getInstance().queryAppointmentOrderStatus( BaseApplication.currentOrderId, new BaseObserver<String>() {

            @Override
            public void onSuccess(String result) {
                tv_result.setText( "支付成功" );
            }

            @Override
            public void onError(@NotNull Throwable e) {
                tv_result.setText( "支付失败" );
            }
        } );
    }


    private void queryPrepaidOrder() {
        RestProxy.getInstance().queryPrepaidOrder( BaseApplication.currentOrderId, new BaseObserver<String>() {
            @Override
            public void onSuccess(String result) {

            }
        } );
    }

    @Override
    public void onBackPressed() {

    }

    /**
     * 定时循环任务
     */
    private Handler mHandler = new Handler( Looper.getMainLooper() ); // 全局变量
    private Runnable mTimeCounterRunnable = new Runnable() {
        @Override
        public void run() {//在此添加需轮寻的接口
            queryOrderStatus();
            mHandler.postDelayed( this, 2 * 1000 );
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimeCounterRunnable != null) {
            mHandler.removeCallbacks( mTimeCounterRunnable );
        }
    }
}